package com.walkline.screen;

import java.util.Hashtable;
import java.util.Vector;

import localization.WeiboSDKResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.util.StringProvider;

import com.walkline.util.Enumerations.NeedComment;
import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Function;
import com.walkline.util.StringUtility;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.container.RepostListStyleButtonSet;
import com.walkline.util.network.DownloadRepostAvatarImages;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.MyLabelField;
import com.walkline.util.ui.MyTextField;
import com.walkline.util.ui.RepostListStyleButtonField;
import com.walkline.weibo.BasicAsyncCallback;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.Comment;
import com.walkline.weibo.inf.CommentWrapper;
import com.walkline.weibo.inf.RepostWrapper;
import com.walkline.weibo.inf.Status;

public class RepostReplyStatusMainScreen extends MainScreen implements WeiboSDKResource
{
	private static ResourceBundle _bundle = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	private WeiboSDK _weibo;
	private WorkQueue _queue = new WorkQueue(2);
	private ShowEmotionPopupScreen emotionScreen = new ShowEmotionPopupScreen();
	private ForegroundManager _foreground = new ForegroundManager(0);
	private RepostListStyleButtonSet _listSet = new RepostListStyleButtonSet();
	private RepostListStyleButtonField _item;

	private MyTextField _statusField;
	private CheckboxField _checkCurrentUser;
	private CheckboxField _checkOriginalUser;

	private Status _status;
	private Comment _comment;
	private String _current_user = "";
	private String _original_user = null;

	private boolean _is_repost;
	private boolean _is_retweeted;
	private String _preset_text;

	public RepostReplyStatusMainScreen(WeiboSDK weibo, Comment comment)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;
		_comment = comment;

		setPresetText("回复@" + comment.getUser().getScreenName() + ":");
		String tipsText = "@" + comment.getUser().getScreenName() + ":" + comment.getText();

		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField("评论"));
		setTitle(hfm);

		_statusField = new MyTextField();
		_statusField.setText(getPresetText());
		_statusField.setCursorPosition(_statusField.getTextLength());
		_statusField.setMaxSize(200);
		_statusField.setPadding(3, 3, 3, 3);
		_statusField.setMargin(10, 3, 3, 3);

		ButtonField btnSubmit = new ButtonField("提交", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		btnSubmit.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				Hashtable params = new Hashtable();
				String newText = _statusField.getText();
				String tempText;

				if (newText.trim().equals("") || (tempText = newText.trim()).equals(getPresetText()))
				{
					Function.errorDialog("回复内容不能为空");
					_statusField.setFocus();

					return;
				}

				if (StringUtility.getUnicodeLength(newText) > 140)
				{
					Function.errorDialog("内容超出字数限制，不要超过140字");
					_statusField.setFocus();

					return;
				}

				params.put("id", _comment.getStatus().getIdStr());
				params.put("cid", _comment.getIdStr());
				params.put("comment", newText);
				//params.put("without_mention", "1");
				params.put("comment_ori", "0");

				if (sendCommentReply(params));
				{
					net.rim.device.api.ui.component.Status.show("发送成功", 1000);
					onClose();
				}
			}
		});
		btnSubmit.setMargin(5, 5, 5, 10);

		_foreground.add(new MyLabelField(tipsText));
		_foreground.add(_statusField);
		_foreground.add(btnSubmit);
		add(_foreground);
	}

	public RepostReplyStatusMainScreen(WeiboSDK weibo, Status status, boolean isRepost)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		_weibo = weibo;
		_status = status;
		_is_repost = isRepost;
		_is_retweeted = status.getRetweetedStatus() != null;
		_preset_text = isRetweeted() ? "//@" + status.getUser().getScreenName() + ":" + status.getText() : "";

		String tipsText;

		if (isRepost())
		{
			tipsText = isRetweeted() ? "@" + status.getRetweetedStatus().getUser().getScreenName() + ":" + status.getRetweetedStatus().getText() : "@" + status.getUser().getScreenName() + ":" + status.getText();	
		} else {
			tipsText = "@" + status.getUser().getScreenName() + ":" + status.getText();
		}

		_current_user = status.getUser().getScreenName();
		_original_user = isRetweeted() ? status.getRetweetedStatus().getUser().getScreenName() : null;

		HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
		hfm.add(new LabelField(isRepost() ? "转发微博" : "评论"));
		setTitle(hfm);

		_listSet.setMargin(0, -1, 0, -1);

		_statusField = new MyTextField();
		_statusField.setText(isRepost() ? getPresetText() : "");
		_statusField.setMaxSize(200);
		_statusField.setPadding(3, 3, 3, 3);
		_statusField.setMargin(10, 3, 3, 3);

		ButtonField btnSubmit = new ButtonField("提交", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
		btnSubmit.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				String newText = _statusField.getText();

				if (StringUtility.getUnicodeLength(newText) > 140)
				{
					Function.errorDialog("内容超出字数限制，不要超过140字");
					_statusField.setFocus();

					return;
				}

				Hashtable params = new Hashtable();

				if (isRepost())
				{
					String is_comment;
					boolean current_user = _checkCurrentUser.getChecked();
					boolean original_user = _checkOriginalUser != null ? _checkOriginalUser.getChecked() : false;

					if (current_user && original_user)
					{
						is_comment = NeedComment.ALL;
					} else if (current_user || original_user) {
						if (!current_user)
						{
							is_comment = NeedComment.ORIGINAL;
						} else {
							is_comment = NeedComment.CURRENT;
						}
					} else {
						is_comment = NeedComment.NONE;
					}

					if (isRetweeted())
					{
						if (getPresetText().equals(newText))
						{
							if (StringUtility.getUnicodeLength(getPresetText()) + 4 > 140)
							{
								Function.errorDialog("内容超出字数限制，不要超过140字");
								_statusField.setFocus();

								return;
							} else {
								newText = "转发微博" + newText;
							}							
						}
					} else {
						if (newText.equals(""))
						{
							newText = "转发微博";
						}
					}

					params.put("id", _status.getIdStr());
					params.put("status", newText);
					params.put("is_comment", is_comment);

					if (sendStatusRepost(params));
					{
						net.rim.device.api.ui.component.Status.show("发送成功", 1000);
						onClose();
					}
				} else {
					String tempText;
					String comment_ori;
					boolean original_user = _checkOriginalUser != null ? _checkOriginalUser.getChecked() : false;

					//CURRENT为借用参数值1，代表需要评论给原文，在此不代表当前用户
					comment_ori = original_user ? NeedComment.CURRENT : NeedComment.NONE;

					if (newText.trim().equals("") || (tempText = newText.trim()).equals(getPresetText()))
					{
						Function.errorDialog("回复内容不能为空");
						_statusField.setFocus();

						return;
					}

					if (StringUtility.getUnicodeLength(newText) > 140)
					{
						Function.errorDialog("内容超出字数限制，不要超过140字");
						_statusField.setFocus();

						return;
					}

					if (_comment == null)
					{
						params.put("id", _status.getIdStr());
						params.put("comment", newText);
						params.put("comment_ori", comment_ori);

						if (sendStatusReply(params));
						{
							net.rim.device.api.ui.component.Status.show("发送成功", 1000);
							onClose();
						}
					} else {
						params.put("id", _status.getIdStr());
						params.put("cid", _comment.getIdStr());
						params.put("comment", newText);
						//params.put("without_mention", "1");
						params.put("comment_ori", comment_ori);

						if (sendCommentReply(params));
						{
							net.rim.device.api.ui.component.Status.show("发送成功", 1000);
							onClose();
						}
					}
				}
			}
		});
		btnSubmit.setMargin(5, 5, 5, 10);

		_foreground.add(new MyLabelField(tipsText));
		_foreground.add(_statusField);
		_foreground.add(btnSubmit);

		if (isRepost())
		{
			_checkCurrentUser = new CheckboxField("同时评论给 " + _current_user, false);
			_foreground.add(_checkCurrentUser);

			if (isRetweeted())
			{
				_checkOriginalUser = new CheckboxField("同时评论给原文作者 " + _original_user, false);
				_foreground.add(_checkOriginalUser);
			}

			add(_foreground);

			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					_weibo.getRepostTimeline(_status.getId(), 10, 1, new getRepostTimelineCallback(), null);
				}
			});
		} else {
			if (isRetweeted())
			{
				_checkOriginalUser = new CheckboxField("同时评论给原文作者 " + _original_user, false);
				_foreground.add(_checkOriginalUser);
			}

			add(_foreground);

			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					_weibo.getCommentsTimeline(_status.getId(), 20, 1, new getCommentTimelineCallback(), null);
				}
			});
		}
	}

	private boolean isRepost() {return _is_repost;}

	private boolean isRetweeted() {return _is_retweeted;}

	private String getPresetText() {return _preset_text;}

	private void setPresetText(String text) {_preset_text = text;}

	/**
	 * 发送一条转发微博
	 */
	private boolean sendStatusRepost(Hashtable params)
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.REPOSTSTATUS);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Status status = popupScreen.getStatus();

		if (popupScreen != null) {popupScreen = null;}

		return status != null;
	}

	/**
	 * 发送一条微博评论
	 */
	private boolean sendStatusReply(Hashtable params)
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.REPLYSTATUS);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Comment comment = popupScreen.getComment();

		if (popupScreen != null) {popupScreen = null;}

		return comment != null;
	}

	/**
	 * 回复一条微博的评论
	 */
	private boolean sendCommentReply(Hashtable params)
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.REPLYCOMMENT);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Comment comment = popupScreen.getComment();

		if (popupScreen != null) {popupScreen = null;}

		return comment != null;
	}

	/**
	 * 获取一个表情符号
	 */
	private void getEmotion()
	{
		UiApplication.getUiApplication().pushModalScreen(emotionScreen);

		_statusField.insert(emotionScreen.getEmotion());
	}

	/**
	 * 获取一个@用户时的联想建议
	 */
	private void getSuggestionUser()
	{
		SuggestionUserPopupScreen popupScreen = new SuggestionUserPopupScreen(_weibo);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		_statusField.insert(popupScreen.getSuggestUser());
	}

	private void refreshRepostTimeline(RepostWrapper repostWrapper)
	{
		Vector reposts = repostWrapper.getReposts();

		//_foreground.add(new LabelField("当前已转发" + repost.getRepostsCount()));

		if (reposts.size() > 0)
		{
			Status repost;
			for (int i=0; i<reposts.size(); i++)
			{
				repost = (Status) reposts.elementAt(i);

				if (!repost.getText().equals("转发微博"))
				{
					_item = new RepostListStyleButtonField(repost);
					_listSet.add(_item);					
				}
			}				

			if (_listSet.getFieldCount() > 0)
			{
				_foreground.add(_listSet);

				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run() {refreshUserListIcons();}
				});

			}
		}
	}

	private void refreshCommentTimeline(CommentWrapper commentWrapper)
	{
		Vector comments = commentWrapper.getComments();

		//_foreground.add(new LabelField("当前已转发" + repost.getRepostsCount()));

		if (comments.size() > 0)
		{
			Comment comment;
			for (int i=0; i<comments.size(); i++)
			{
				comment = (Comment) comments.elementAt(i);

				if (!comment.getText().equals("转发微博"))
				{
					_item = new RepostListStyleButtonField(comment);
					_listSet.add(_item);					
				}
			}

			if (_listSet.getFieldCount() > 0)
			{
				_foreground.add(_listSet);

				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run() {refreshUserListIcons();}
				});

			}
		}
	}

	private void refreshUserListIcons()
    {
		RepostListStyleButtonField item;

		_queue.removeAll();

		for (int i=0; i<_listSet.getFieldCount(); i++)
		{
			Field object = _listSet.getField(i);

			if (object instanceof RepostListStyleButtonField)
			{
				item = (RepostListStyleButtonField) object;
				_queue.execute(new DownloadRepostAvatarImages(_weibo, item));
			}
		}
    }

	/**
	 * 从转发列表里选取一条微博进行转发
	 */
	private void setStatusRepost()
	{
		if (isRepost() && _listSet.getFieldCount() > 0)
		{
			RepostListStyleButtonField item;
			item = (RepostListStyleButtonField) _listSet.getFieldWithFocus();

			setPresetText("//@" + item.getStatus().getUser().getScreenName() + ":" + item.getStatus().getText());

			_statusField.setText(getPresetText());
			_statusField.setFocus();
			_statusField.setCursorPosition(0);
		}
	}

	/**
	 * 从评论列表里选取一条评论进行回复
	 */
	private void setStatusReply()
	{
		if (_listSet.getFieldCount() > 0)
		{
			RepostListStyleButtonField item;
			item = (RepostListStyleButtonField) _listSet.getFieldWithFocus();
			_comment = item.getComment();

			setPresetText("回复@" + item.getComment().getUser().getScreenName() + ":");

			_statusField.setText(getPresetText());
			_statusField.setFocus();
		}
	}

	private void showUserHomepage()
	{
		if (_listSet.getFieldCount() > 0)
		{
			RepostListStyleButtonField item = (RepostListStyleButtonField) _listSet.getFieldWithFocus();

			UiApplication.getUiApplication().pushScreen(new HomePageMainScreen(_weibo, item.getUser()));
		}
	}

	class getRepostTimelineCallback extends BasicAsyncCallback
	{
		public void onComplete(final RepostWrapper value, Object state)
		{
			if (value != null)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run() {refreshRepostTimeline(value);}
				});
			}
		}

		public void onException(Exception e, Object state)
		{
			Function.errorDialog(e.toString());
		}
	}

	class getCommentTimelineCallback extends BasicAsyncCallback
	{
		public void onComplete(final CommentWrapper value, Object state)
		{
			if (value != null)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run() {refreshCommentTimeline(value);}
				});
			}
		}

		public void onException(Exception e, Object state)
		{
			Function.errorDialog(e.toString());
		}
	}

	MenuItem menuInsertEmotion = new MenuItem(new StringProvider("插入表情(alt+sym)"), 100, 10)
	{
		public void run() {getEmotion();}
	};

	MenuItem menuUserHomepage = new MenuItem(_bundle, MENU_SHOW_USER_HOMEPAGE, 100, 20)
	{
		public void run(){showUserHomepage();} 
	};

	MenuItem menuRepostStatus = new MenuItem(_bundle, MENU_STATUS_REPOST, 100, 20)
    {
    	public void run() {setStatusRepost();}
    };

    MenuItem menuReplyStatus = new MenuItem(_bundle, MENU_STATUS_REPLY, 100, 30)
    {
    	public void run() {setStatusReply();}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	if (_statusField.isFocus()) {menu.add(menuInsertEmotion);}

    	if (_listSet.getFieldCount() > 0)
    	{
    		if (_listSet.getFieldWithFocus() != null)
    		{
    			menu.add(menuUserHomepage);

    			if (isRepost())
    			{
    				//menu.add(menuRepostStatus);		
    			} else {
    				menu.add(menuReplyStatus);    				
    			}
    		}
    	}

    	super.makeMenu(menu, instance);
    }

    protected boolean keyDown(int keycode, int time)
	{
		if (_statusField.isFocus())
		{
			if (keycode == 8323073) //alt + sym
			{
				getEmotion();
				return true;
			} else if (keycode == 5242881) { //alt + p
				_statusField.backspace(1);
				getSuggestionUser();
				return true;
			}
		}

		return super.keyDown(keycode, time);
	}

    protected boolean keyChar(char key, int status, int time)
    {
    	if (_statusField.isFocus())
		{
    		switch (key)
    		{
				case Characters.COMMERCIAL_AT:
					getSuggestionUser();
					return true;
			}
		} else if (_listSet.getFieldWithFocus() != null) {
    		switch (key)
        	{
    			case Characters.LATIN_CAPITAL_LETTER_R:
    			case Characters.LATIN_SMALL_LETTER_R:
    				return true;
    			case 'd':
    				setStatusReply();
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_F:
    			case Characters.LATIN_SMALL_LETTER_F:
    				return true;
    			case 'u':
    				showUserHomepage();
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_A:
    			case Characters.LATIN_SMALL_LETTER_A:
    				return true;
    			case 'q':
    				Function.showExitDialog();
    				return true;
    		}	
    	}

    	return super.keyChar(key, status, time);
    }

    public boolean onClose()
    {
    	_queue.removeAll();

    	return super.onClose();
    }

	protected boolean onSavePrompt() {return true;}
}